package cn.edu.jmu.oelp.service.impl;

import cn.edu.jmu.oelp.pojo.EntityRelation;
import cn.edu.jmu.oelp.repository.EntityRelationRepository;
import cn.edu.jmu.oelp.repository.EntityRepository;
import cn.edu.jmu.oelp.service.EntityRelationNeo4jService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author damao
 */
@Service
public class EntityRelationNeo4jServiceImpl implements EntityRelationNeo4jService {

    @Autowired
    private EntityRepository entityRepo;
    @Autowired
    private EntityRelationRepository relationRepo;

    @Override
    public EntityRelation addRelation(EntityRelation entityRelation) {
        entityRelation.setStartEntity(entityRepo.findByEntityId(entityRelation.getStartId()));
        entityRelation.setEndEntity(entityRepo.findByEntityId(entityRelation.getEndId()));
        return relationRepo.save(entityRelation);
    }

    @Override
    public void delRelation(Long relationId) {
        EntityRelation entityRelation = relationRepo.findByRelationId(relationId);
        relationRepo.delete(entityRelation);
        System.out.println(entityRelation + "\n删除成功");
    }

    /**
     * 先删旧关系，再添加新关系
     * @param entityRelation
     */
    @Override
    public void updateRelation(EntityRelation entityRelation) {
        relationRepo.delete(relationRepo.findByRelationId(entityRelation.getRelationId()));
        EntityRelation relation = new EntityRelation(entityRelation.getStartId(),entityRelation.getEndId(),entityRelation.getType());
        relation.setRelationId(entityRelation.getRelationId());
        relation.setStartEntity(entityRepo.findByEntityId(entityRelation.getStartId()));
        relation.setEndEntity(entityRepo.findByEntityId(entityRelation.getEndId()));
        relationRepo.save(relation);
        System.out.println("update to neo4j");
    }

    @Override
    public List<EntityRelation> findAll() {
        return relationRepo.findAll();
    }

    @Override
    public EntityRelation findById(long id) {
        return relationRepo.findById(id);
    }

    @Override
    public List<EntityRelation> findByStartEntityId(long startId) {
        return relationRepo.findByStartEntityId(startId);
    }

    @Override
    public List<EntityRelation> findByEndEntityId(long endId) {
        return relationRepo.findByEndEntityId(endId);
    }

    @Override
    public List<EntityRelation> findByType(String type) {
        return relationRepo.findByType(type);
    }

    @Override
    public List<EntityRelation> findByStartEntityIdAndEndEntityId(long startEntityId, long endEntityId) {
        return relationRepo.findByStartEntityIdAndEndEntityId(startEntityId,endEntityId);
    }

    @Override
    public EntityRelation findByStartEntityIdAndEndEntityIdAndType(long startEntityId, long endEntityId, String type) {
        return relationRepo.findByStartEntityIdAndEndEntityIdAndType(startEntityId, endEntityId,type);
    }
}
